﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Web;
using System.Text.RegularExpressions;

namespace AjaxSnippets
{
    /// <summary>
    /// Provides snippets
    /// </summary>
    public static class SnippetProvider
    {
        /// <summary>
        /// Get a snippet
        /// </summary>
        /// <param name="snippetId">used as the naming container, all controls in the snippet
        /// will have their client id's prefixed with this</param>
        /// <param name="virtualPath">The virtual path to an ascx file that derives from SnippetControl</param>
        /// <returns>the compiled snippet</returns>
        public static string GetSnippet(string snippetId, string virtualPath)
        {
            Page holder = new Page();
            Control snippetControl = (Control)holder.LoadControl(virtualPath);

            if (!(snippetControl is SnippetControl))
                throw new ArgumentException("ascx must derive from SnippetControl", "virtualPath");

            snippetControl.ID = snippetId;
            HtmlForm form = new HtmlForm();
            holder.Controls.Add(form);
            ScriptManager scriptManager = new ScriptManager();
            scriptManager.ID = "ScriptManager";
            form.Controls.Add(scriptManager);
            form.Controls.Add(snippetControl);
            StringWriter writer = new StringWriter();
            HttpContext.Current.Server.Execute(holder, writer, false);
            Regex regEx = new Regex(@"(?<=<snippet>)(.*)(?=</snippet>)", RegexOptions.Singleline);
            string result = regEx.Match(writer.ToString()).Value;
            return result;
        }
    }
}
